<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2017/9/21
 * Time: 17:01
 */
//获取目录所有文件信息
function myGetFilesInfo($dir){
    $lists = scandir($dir);
    $data = [];
    foreach($lists as $item){
        $fullPath = $dir.$item;
        if (!is_dir($fullPath)){
            $fileContent = file_get_contents($fullPath);
            $title = strstr($fileContent,PHP_EOL,true);
            $content = strstr($fileContent,PHP_EOL);
            $data[] = [
                'filename' => $item,
                'title'=> $title,
                'content'=>$content
            ];
        }
    }
    return $data;
}

/**
 * @param $dir 目录
 * @return array 返回 所有的文件名信息到一个数组中
 */
function getFileNames($dir){
    $lists = scandir($dir);
    $data = [];
    foreach($lists as $item){
        $fullPath = $dir.$item;
        if (!is_dir($fullPath)){
            $data[] = $item;
        }
    }
    return $data;
}
/**
 * @param $dir 文件夹名
 * @param $filename 如 1.txt这样的文件名
 */
function getOneFileInfo($dir,$filename){
    $data = [];
    $fullPath = $dir.$filename;
    if (file_exists($fullPath)){
        $fileContent = file_get_contents($fullPath);
        $title = strstr($fileContent,PHP_EOL,true);
        $content = strstr($fileContent,PHP_EOL);
        $data['filename'] = $filename;
        $data['title'] = $title;
        $data['content']= $content;
    }
    return $data;
}

/**
 * 返回一个新创建的文件名
 * @param $dir
 * @return string
 */
function createNewFile($dir){
    $newFileName = '';
    $fileNameInfo = getFileNames($dir);
    $i = 0;
    foreach($fileNameInfo as $item){
        if ((int)$item>$i){
            $i = (int)$item;
        }
    }
    return ($i+1).".txt";
}

/**
 * 新发布博客时，用这个来保存文件
 * @param $dir
 * @param $title
 * @param $content
 * @return bool 保存成功返回true,否则返回false
 */
function saveInfo($dir,$title,$content){
    $newFileName = createNewFile($dir);
    $fullPath = $dir.$newFileName;
    $s = $title.PHP_EOL.$content;
    if (file_put_contents($fullPath,$s)){
        return true;
    } else {
        return false;
    }
}

/**
 * 新发布博客时，用这个来保存文件
 * @param $dir
 * @param $title
 * @param $content
 * @return bool 保存成功返回true,否则返回false
 */
function editInfo($fullPath,$title,$content){
    $s = $title.PHP_EOL.$content;
    if (file_put_contents($fullPath,$s)){
        return true;
    } else {
        return false;
    }
}


function delBlog($dir,$fileName){
   $fullPath = $dir.$fileName;
    if (file_exists($fullPath)){
        if (unlink($fullPath)){
            return true;
        } else {
            return false;
        }

    } else {
        return true;
    }
}